﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace YJYpublicClass
{
    class SaveCSV
    {
        public static bool SaveResultMsg(string lotID, string resultMsg)
        {
            //***********************************************
            //                                              *
            //   Use this one with the data correction      *
            //                                              *
            //***********************************************

            bool res = false;

            string s_FileName = lotID + "_" + DateTime.Now.ToString("yyyyMMdd") + ".csv";

            string FileName = CreateLotFolder(lotID) + s_FileName;
            string columnTitle = "";
            string columnValue = "";

            FileStream objFileStream = null;
            StreamWriter sw = null;

            bool bCreatedNew = false;

            try
            {
                if (!File.Exists(FileName))
                {
                    objFileStream = new FileStream(FileName, FileMode.CreateNew, FileAccess.Write);
                    bCreatedNew = true;
                }
                else
                {
                    File.SetAttributes(FileName, File.GetAttributes(FileName) & ~FileAttributes.ReadOnly);

                    objFileStream = new FileStream(FileName, FileMode.Append, FileAccess.Write);
                }
                sw = new StreamWriter(objFileStream, System.Text.Encoding.GetEncoding(-0));


                if (bCreatedNew)
                {
                    //header
                    columnTitle = lotID;
                    sw.WriteLine(columnTitle);               
                }

                //the test data
                columnValue = resultMsg;

                sw.WriteLine(columnValue);

                sw.Close();
                objFileStream.Close();
            }
            catch (Exception e)
            {
                res = false;
            }
            finally
            {
                sw.Close();
                objFileStream.Close();
            }
            return res;
        }

        private static string CreateLotFolder(string lotID)
        {


            //LG Format
            string path = "D:\\TestData" + "\\" + DateTime.Now.ToString("yyyyMMdd");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            //Config
            string ConfigPath = path + "\\" + lotID;
            if (!Directory.Exists(ConfigPath))
            {
                Directory.CreateDirectory(ConfigPath);
            }
            return ConfigPath + "\\";
        }      
      
    }
}
